package cn.edut.web.servlet;

import cn.edut.dao.UserDao;
import cn.edut.domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @Author ruanxin
 */

@WebServlet("loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置编码
        req.setCharacterEncoding("utf-8");
       /* //2.获取请求参数
        String username = req.getParameter("username");
        String userpassword = req.getParameter("userpassword");
        //3.封装user对象
        User loginuser= new User();
        loginuser.setUsername(username);
        loginuser.setUserpassword(userpassword);*/
        //获取所有请求参数
        Map<String, String[]> map = req.getParameterMap();
        //创建user对象
        User loginuser=new User();
      //使用BeanUtil对象封装
        try {
            BeanUtils.populate(loginuser,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //4.调用UserDao的login方法
        UserDao userDao=new UserDao();
        User user = userDao.login(loginuser);

        //5.判断user
        if(user == null)
        {
            req.getRequestDispatcher("/failServlet").forward(req,resp);
        }else {
            req.getRequestDispatcher("/successServlet").forward(req,resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    this.doGet(req,resp);
    }
}
